// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: Apache-2.0

package resource_dao

import (
	"context"
	"fmt"

	"gitcode.com/lvupclub/lvup-api/dao/common"
	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
)

type CardLinkDbItem struct {
	ObjectId   string `bson:"_id"`
	ResourceId string `bson:"resourceId"`
	CardId1    string `bson:"cardId1"`
	CardId2    string `bson:"cardId2"`
}

type _CardLinkDao struct {
	mc *mongo.Collection
}

func newCardLinkDao(db *mongo.Database) (*_CardLinkDao, error) {
	mc := db.Collection(common.DB_NS_RESOURCE + "card_link")
	_, err := mc.Indexes().CreateMany(context.Background(), []mongo.IndexModel{
		{
			Keys: bson.D{{"resourceId", 1}, {"cardId1", 1}},
		},
		{
			Keys: bson.D{{"resourceId", 1}, {"cardId2", 1}},
		},
	})
	if err != nil {
		return nil, err
	}
	return &_CardLinkDao{mc: mc}, nil
}

func (db *_CardLinkDao) genObjectId(cardId1, cardId2 string) string {
	return fmt.Sprintf("%s:%s", cardId1, cardId2)
}

func (db *_CardLinkDao) Insert(ctx context.Context, dbItem *CardLinkDbItem) error {
	dbItem.ObjectId = db.genObjectId(dbItem.CardId1, dbItem.CardId2)
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_CardLinkDao) Exist(ctx context.Context, resourceId, cardId1, cardId2 string) (bool, error) {
	objectId := db.genObjectId(cardId1, cardId2)
	count, err := db.mc.CountDocuments(ctx, bson.M{"_id": objectId, "resourceId": resourceId})
	return count > 0, err
}

func (db *_CardLinkDao) Remove(ctx context.Context, resourceId, cardId1, cardId2 string) error {
	objectId := db.genObjectId(cardId1, cardId2)
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": objectId, "resourceId": resourceId})
	if err != nil {
		return err
	}
	objectId = db.genObjectId(cardId2, cardId1)
	_, err = db.mc.DeleteOne(ctx, bson.M{"_id": objectId, "resourceId": resourceId})
	return err
}

func (db *_CardLinkDao) RemoveByCard(ctx context.Context, resourceId, cardId string) error {
	_, err := db.mc.DeleteMany(ctx, bson.M{"cardId1": cardId, "resourceId": resourceId})
	if err != nil {
		return err
	}
	_, err = db.mc.DeleteMany(ctx, bson.M{"cardId2": cardId, "resourceId": resourceId})
	return err
}

func (db *_CardLinkDao) RemoveByResource(ctx context.Context, resourceId string) error {
	_, err := db.mc.DeleteMany(ctx, bson.M{"resourceId": resourceId})
	return err
}

func (db *_CardLinkDao) List(ctx context.Context, resourceId string, cardIdList []string) ([]*CardLinkDbItem, error) {
	if len(cardIdList) == 0 {
		return []*CardLinkDbItem{}, nil
	}
	cursor, err := db.mc.Find(ctx, bson.M{"cardId1": bson.M{"$in": cardIdList}, "resourceId": resourceId})
	if err != nil {
		return nil, err
	}
	retList := []*CardLinkDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}
